package com.zh.business.service.mp.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.business.service.mp.TaxiOrderInfoService;
import com.zh.zhbootcommon.common.CommonKey;
import com.zh.zhbootcommon.entity.taxi.DTaxiAddressInfo;
import com.zh.zhbootcommon.entity.taxi.DTaxiOrderInfo;
import com.zh.zhbootcommon.entity.taxi.DUserOrderRelation;
import com.zh.business.mapper.taxi.DTaxiAddressInfoMapper;
import com.zh.business.mapper.taxi.DTaxiOrderInfoMapper;
import com.zh.business.mapper.taxi.DUserOrderRelationMapper;
import com.zh.business.vo.mp.TaxiOrderRep;
import com.zh.business.vo.mp.TaxiOrderReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 打车订单表 服务实现类
 * </p>
 *
 * @author JueDream
 * @since 2021-08-04
 */
@Service
public class TaxiOrderInfoServiceImpl extends ServiceImpl<DTaxiOrderInfoMapper, DTaxiOrderInfo> implements TaxiOrderInfoService {

    @Autowired
    DTaxiOrderInfoMapper orderInfoMapper;

    @Autowired
    DTaxiAddressInfoMapper addressInfoMapper;

    @Autowired
    DUserOrderRelationMapper userOrderRelationMapper;


    @Override
    public Page<TaxiOrderRep> queryTaxiOrderWechat(Integer page, Integer limit, TaxiOrderReq orderReq) {
        Page<TaxiOrderRep> taxiOrderRepPage = new Page<>(page, limit);
        List<TaxiOrderRep> orderReps = new ArrayList<>();
        Page<DTaxiOrderInfo> orderInfoPage = new Page<>(page, limit);
        // 角色分类(0-司机; 1-乘客)
        LambdaQueryWrapper<DUserOrderRelation> queryUOWrapper = new LambdaQueryWrapper<DUserOrderRelation>();
        // 根据openId查询用户订单关系
        if ("0".equals(orderReq.getMType())) {
            queryUOWrapper.eq(DUserOrderRelation::getDOpenId, orderReq.getDOpenId());
        }else if ("1".equals(orderReq.getMType())) {
            queryUOWrapper.eq(DUserOrderRelation::getMOpenId, orderReq.getMOpenId());
        }
        List<DUserOrderRelation> userOrderRelations = userOrderRelationMapper.selectList(queryUOWrapper);
        List<Integer> orderIds = userOrderRelations.stream().map(rp -> rp.getOrderId()).collect(Collectors.toList());
        LambdaQueryWrapper<DTaxiOrderInfo> queryTOWrapper = new LambdaQueryWrapper();
        if (orderIds.size() > 0) {
            queryTOWrapper.in(DTaxiOrderInfo::getOrderId, orderIds);
            // 订单状态 10-已完成(10-60) 20-已取消(80) 30-正在进行(70)
            if (CommonKey.ORDER_STATUS_10.getValue().equals(orderReq.getOrderStatus())){
                String status = "10,20,30,40,50,60";
                queryTOWrapper.in(DTaxiOrderInfo::getOrderStatus, status.split(","));
            }else if (CommonKey.ORDER_STATUS_20.getValue().equals(orderReq.getOrderStatus())) {
                queryTOWrapper.eq(DTaxiOrderInfo::getOrderStatus, CommonKey.ORDER_STATUS_80.getValue());
            }else if (CommonKey.ORDER_STATUS_30.getValue().equals(orderReq.getOrderStatus())) {
                queryTOWrapper.eq(DTaxiOrderInfo::getOrderStatus, CommonKey.ORDER_STATUS_70.getValue());
            }
            orderInfoPage = orderInfoMapper.selectPage(orderInfoPage, queryTOWrapper);
            orderInfoPage.setTotal(orderInfoPage.getRecords().size());
            // 重新构造数据
            Optional.ofNullable(orderInfoPage.getRecords()).orElse(new ArrayList<>())
                    .forEach(o -> {
                        TaxiOrderRep orderRep = this.mergeOrderRep(o);
                        orderReps.add(orderRep);
                    });
            taxiOrderRepPage.setRecords(orderReps);
            taxiOrderRepPage.setTotal(orderReps.size());
        }
        return taxiOrderRepPage;
    }

    @Override
    public TaxiOrderRep queryTaxiOrderWechatDetail(TaxiOrderReq orderReq) {
        LambdaQueryWrapper<DTaxiOrderInfo> queryTOWrapper = new LambdaQueryWrapper();
        if (StrUtil.isNotBlank(orderReq.getOrderCode())){
            queryTOWrapper.eq(DTaxiOrderInfo::getOrderCode, orderReq.getOrderCode());
        }
        if (Objects.nonNull(orderReq.getOrderId())){
            queryTOWrapper.eq(DTaxiOrderInfo::getOrderId, orderReq.getOrderId());
        }
        DTaxiOrderInfo orderInfo = null;
        if (queryTOWrapper.nonEmptyOfNormal()) {
            orderInfo = orderInfoMapper.selectOne(queryTOWrapper);
        }
        TaxiOrderRep orderRep = this.mergeOrderRep(orderInfo);
        return orderRep;
    }

    @Override
    public boolean updateOrderStatus(Integer orderId, Integer orderStatus) {
        boolean flag = false;
        DTaxiOrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (Objects.nonNull(orderInfo)) {
            orderInfo.setOrderStatus(orderStatus);
            int result = orderInfoMapper.updateById(orderInfo);
            if (result > 0) {
                flag = true;
            }
        }
        return flag;
    }

    @Override
    public boolean updateOrderStatus(String orderCode, Integer orderStatus) {
        boolean flag = false;
        DTaxiOrderInfo orderInfo = new DTaxiOrderInfo();
        LambdaQueryWrapper<DTaxiOrderInfo> queryWrapper = new LambdaQueryWrapper<DTaxiOrderInfo>();
        if (StrUtil.isNotBlank(orderCode)) {
            queryWrapper.eq(DTaxiOrderInfo::getOrderCode, orderCode);
            queryWrapper.eq(DTaxiOrderInfo::getDelFlg, "0");
            orderInfo = orderInfoMapper.selectOne(queryWrapper);
        }
        if (Objects.nonNull(orderInfo)) {
            orderInfo.setOrderStatus(orderStatus);
            int result = orderInfoMapper.updateById(orderInfo);
            if (result > 0) {
                flag = true;
            }
        }
        return flag;
    }

    @Override
    public boolean updateUserOrderRelation(Integer orderId, String dOpenId) {
        boolean flag = false;
        LambdaQueryWrapper<DUserOrderRelation> queryUOWrapper = new LambdaQueryWrapper<DUserOrderRelation>();
        queryUOWrapper.eq(DUserOrderRelation::getOrderId, orderId);
        DUserOrderRelation userOrderRelation = userOrderRelationMapper.selectOne(queryUOWrapper);
        if (Objects.nonNull(userOrderRelation)) {
            userOrderRelation.setDOpenId(dOpenId);
            int result = userOrderRelationMapper.updateById(userOrderRelation);
            if (result > 0) {
                flag = true;
            }
        }
        return flag;
    }

    @Override
    public DTaxiOrderInfo getOrderInfo(Integer orderId) {
        return orderInfoMapper.selectById(orderId);
    }

    @Override
    public DTaxiOrderInfo getOrderInfoByCode(String orderCode) {
        DTaxiOrderInfo orderInfo = new DTaxiOrderInfo();
        LambdaQueryWrapper<DTaxiOrderInfo> queryWrapper = new LambdaQueryWrapper<DTaxiOrderInfo>();
        if (StrUtil.isNotBlank(orderCode)) {
            queryWrapper.eq(DTaxiOrderInfo::getOrderCode, orderCode);
            queryWrapper.eq(DTaxiOrderInfo::getDelFlg, "0");
        }
        if (queryWrapper.nonEmptyOfNormal()) {
            orderInfo = orderInfoMapper.selectOne(queryWrapper);
        }
        return orderInfo;
    }

    /**
     * 合并订单信息
     * @param orderInfo
     * @return
     */
    public TaxiOrderRep mergeOrderRep(DTaxiOrderInfo orderInfo){
        if (Objects.isNull(orderInfo)) {
            return new TaxiOrderRep();
        }
        TaxiOrderRep orderRep = TaxiOrderRep.builder()
                .orderId(orderInfo.getOrderId()).orderCode(orderInfo.getOrderCode())
                .orderPrice(orderInfo.getOrderPrice()).orderStatus(orderInfo.getOrderStatus())
                .orderTaxiNum(orderInfo.getOrderTaxiNum()).createTime(orderInfo.getCreateTime())
                .build();
        // 地址信息
        if (orderInfo.getTaxiId() > 0) {
            DTaxiAddressInfo addressInfo = addressInfoMapper.selectById(orderInfo.getTaxiId());
            if (Objects.nonNull(addressInfo)) {
                orderRep.setAddressInfo(addressInfo);
                // 出发点
                orderRep.setTaxiFirstDetail(addressInfo.getTaxiFirstDetail());
                // 终点
                orderRep.setTaxiLastDetail(addressInfo.getTaxiLastDetail());
            }
        }
        // 用户订单关系
        if (orderInfo.getOrderId() > 0) {
            LambdaQueryWrapper<DUserOrderRelation> queryWrapper = new LambdaQueryWrapper<DUserOrderRelation>();
            queryWrapper.eq(DUserOrderRelation::getOrderId, orderInfo.getOrderId());
            DUserOrderRelation orderRelation = userOrderRelationMapper.selectOne(queryWrapper);
            orderRep.setDOpenId(orderRelation.getDOpenId());
            orderRep.setMOpenId(orderRelation.getMOpenId());
        }
        return orderRep;
    }

}
